var SoundManager = function() {
	this.socket = new WebSocket("ws://" + window.location.host + "/websocket");
	this.socket.onopen = this.onOpen.bind(this);
	this.socket.onmessage = this.onMessage.bind(this);
	
	this.soundSources = [];
	this.soundSystems = [];
	
	this.systemsDiv = document.getElementById("soundSystems");
};

SoundManager.prototype.onOpen = function(event) {
	console.log("Web socket opened");
	this.requestSystemInfo();
};

SoundManager.prototype.onMessage = function(event) {
	console.log("Message recieved:");
	console.log(event);
	var data = JSON.parse(event.data);
	if (data.system_info) {
		this.rebuildSystem(data.system_info);
	} else if (data.pandora_stations) {
		this.setPandoraStations(data.pandora_stations);
	}
};

SoundManager.prototype.setPandoraStations = function(pandoraStations) {
	for (var i = 0; i < this.soundSystems.length; i++) {
		this.soundSystems[i].setPandoraStations(pandoraStations);
	}
};

SoundManager.prototype.playAudioSource = function(soundSystem, audioSource) {
	this.socket.send(JSON.stringify({"request":"playSource", "soundSystem":soundSystem,
						    "audioSource":audioSource}));
};

SoundManager.prototype.playPandoraStation = function(soundSystem, pandoraStation) {
	this.socket.send(JSON.stringify({"request":"playSource", "soundSystem":soundSystem,
						    "pandoraStation":pandoraStation}));
};

SoundManager.prototype.pause = function(soundSystem) {
	this.socket.send(JSON.stringify({"request": "pause", "soundSystem" : soundSystem}));
}

SoundManager.prototype.requestSystemInfo = function() {
	this.socket.send(JSON.stringify({"request":"systemInfo"}));
};

SoundManager.prototype.requestPandoraStations = function(soundSystem) {
	this.socket.send(JSON.stringify({"request":"pandoraStations", "soundSystem":soundSystem}));
};

SoundManager.prototype.rebuildSystem = function(systemInfo) {
	this.soundSystems = [];
	this.soundSources = [];
	
	// Clear the existing set of systems
	this.systemsDiv.innerHtml = "";
	
	this.soundSources = systemInfo.soundSources;
	for (var i = 0; i < systemInfo.soundSystems.length; i++) {
		this.soundSystems[i] = new SoundSystem(this, systemInfo.soundSystems[i],
											   this.soundSources, this.systemsDiv);
	}
};

var soundManager;

var onLoad = function(event) {
	soundManager = new SoundManager();
};